<template>
  <el-dialog
    v-model="visible"
    :title="`评分对比 - ${assetIp || ''}`"
    width="1200px"
    destroy-on-close
    @close="handleClose"
  >
    <div v-loading="loading" class="compare-content">
      <!-- 选择对比时间点 -->
      <el-card class="compare-section-card">
        <template #header>
          <span class="section-title">选择对比时间点</span>
        </template>
        <div class="time-selectors">
          <div class="time-select-item">
            <label class="time-label">基准:</label>
            <el-select
              v-model="baseTimeId"
              placeholder="选择基准时间"
              @change="handleTimeChange"
              style="width: 280px"
            >
              <el-option
                v-for="item in historyList"
                :key="item.id"
                :label="`${item.calculated_at || item.score_time} (${
                  item.total_score
                }分)`"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
          <div class="time-select-item">
            <label class="time-label">对比:</label>
            <el-select
              v-model="compareTimeId"
              placeholder="选择对比时间"
              @change="handleTimeChange"
              style="width: 280px"
            >
              <el-option
                v-for="item in historyList"
                :key="item.id"
                :label="`${item.calculated_at || item.score_time} (${
                  item.total_score
                }分)`"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
      </el-card>

      <!-- 总体对比 -->
      <el-card class="compare-section-card" v-if="compareData">
        <template #header>
          <span class="section-title">总体对比</span>
        </template>
        <DynamicTable :columns="overallColumns" :data="overallCompareData" />
      </el-card>

      <!-- 维度对比详情 -->
      <el-card class="compare-section-card" v-if="compareData">
        <template #header>
          <span class="section-title">维度对比详情</span>
        </template>

        <!-- 摘要统计 -->
        <el-alert
          v-if="compareData.summary"
          :type="
            compareData.summary.increased_count > 0 ? 'warning' : 'success'
          "
          :closable="false"
          style="margin-bottom: 20px"
        >
          <template #title>
            <span v-if="compareData.summary.increased_count > 0">
              ⚠️ 有 {{ compareData.summary.increased_count }} 个维度扣分增加，
              共增加 {{ compareData.summary.total_increase.toFixed(1) }} 分
            </span>
            <span
              v-if="compareData.summary.decreased_count > 0"
              style="margin-left: 20px"
            >
              ✅ 有 {{ compareData.summary.decreased_count }} 个维度扣分减少，
              共减少 {{ compareData.summary.total_decrease.toFixed(1) }} 分
            </span>
            <span
              v-if="compareData.summary.unchanged_count > 0"
              style="margin-left: 20px"
            >
              ℹ️ {{ compareData.summary.unchanged_count }} 个维度无变化
            </span>
          </template>
        </el-alert>

        <DynamicTable
          :columns="dimensionColumns"
          :data="dimensionCompareData"
        />
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <!-- <el-button type="primary" @click="handleExportReport"
        >导出对比报告</el-button
      > -->
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, computed, h } from "vue";
import { ElMessage } from "element-plus";
import { DynamicTable } from "@/components/DynamicTable";
import type { TableColumn } from "@/components/DynamicTable/types";
import { getHistoryList, getHistoryCompare } from "../../../servers";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  assetIp: {
    type: String,
    default: "",
  },
  initialIds: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["close", "update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const historyList = ref<any[]>([]);
const baseTimeId = ref<number | string>("");
const compareTimeId = ref<number | string>("");
const compareData = ref<any>(null);

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val && props.assetIp) {
      fetchAssetHistory(props.assetIp);
    }
  },
  { immediate: true }
);

// 监听资产IP变化
watch(
  () => props.assetIp,
  (ip) => {
    if (ip && visible.value) {
      fetchAssetHistory(ip);
    }
  }
);

// 监听时间选择变化
const handleTimeChange = async () => {
  if (baseTimeId.value && compareTimeId.value) {
    await fetchCompareData();
  }
};

// 获取资产历史记录
const fetchAssetHistory = async (ip: string) => {
  if (!ip) return;

  loading.value = true;
  try {
    const params = {
      page: 1,
      page_size: 50,
      filters: {
        asset_ip: ip,
      },
      order_by: "calculated_at" as const,
      order_direction: "desc" as const,
    };
    const { data } = await getHistoryList(params);
    historyList.value = data.items || [];

    // 设置初始选择
    if (props.initialIds.length > 0 && historyList.value.length > 0) {
      baseTimeId.value = props.initialIds[0] as number;
      // 尝试选择第二个不同的记录作为对比
      const compareId = historyList.value.find(
        (item) => item.id !== baseTimeId.value
      )?.id;
      if (compareId) {
        compareTimeId.value = compareId;
        setTimeout(() => {
          fetchCompareData();
        }, 100);
      }
    } else if (historyList.value.length >= 2) {
      baseTimeId.value = historyList.value[0].id;
      compareTimeId.value = historyList.value[1].id;
      setTimeout(() => {
        fetchCompareData();
      }, 100);
    } else if (historyList.value.length === 1) {
      ElMessage.warning("该资产只有一条历史记录，无法进行对比");
    } else {
      ElMessage.warning("该资产没有历史记录");
    }
  } catch (error) {
    console.error("获取资产历史记录失败:", error);
    ElMessage.error("获取资产历史记录失败");
  } finally {
    loading.value = false;
  }
};

// 获取对比数据
const fetchCompareData = async () => {
  if (!baseTimeId.value || !compareTimeId.value || !props.assetIp) return;

  loading.value = true;
  try {
    const { data } = await getHistoryCompare({
      asset_ip: props.assetIp,
      base_history_id: Number(baseTimeId.value),
      compare_history_id: Number(compareTimeId.value),
    });
    compareData.value = data;
  } catch (error) {
    console.error("获取对比数据失败:", error);
    ElMessage.error("获取对比数据失败");
  } finally {
    loading.value = false;
  }
};

// 总体对比表格列配置
const overallColumns = computed<TableColumn[]>(() => [
  {
    label: "对比项",
    prop: "name",
    width: 150,
    show: true,
  },
  {
    label: "基准值",
    prop: "baseValue",
    width: 180,
    show: true,
    render: (row) => {
      if (row.name === "总分") {
        return h(
          "span",
          { class: getScoreClass(row.baseValue) },
          row.baseValue?.toFixed(2) || "-"
        );
      }
      if (row.name === "风险等级") {
        return h("div", { class: "flex items-center" }, [
          h("span", {
            class: `risk-indicator ${getRiskClass(row.baseValue)}`,
          }),
          h("span", getRiskText(row.baseValue)),
        ]);
      }
      return h("span", row.baseValue || "-");
    },
  },
  {
    label: "对比值",
    prop: "compareValue",
    width: 180,
    show: true,
    render: (row) => {
      if (row.name === "总分") {
        return h(
          "span",
          { class: getScoreClass(row.compareValue) },
          row.compareValue?.toFixed(2) || "-"
        );
      }
      if (row.name === "风险等级") {
        return h("div", { class: "flex items-center" }, [
          h("span", {
            class: `risk-indicator ${getRiskClass(row.compareValue)}`,
          }),
          h("span", getRiskText(row.compareValue)),
        ]);
      }
      return h("span", row.compareValue || "-");
    },
  },
  {
    label: "变化",
    prop: "change",
    width: 150,
    show: true,
    render: (row) => {
      if (row.name === "总分") {
        const diff = row.diff || 0;
        const color = diff > 0 ? "#f5222d" : diff < 0 ? "#52c41a" : "#666";
        return h("span", { style: { color, fontWeight: "bold" } }, [
          diff > 0 ? "+" : "",
          diff.toFixed(1),
          " ",
          diff > 0 ? "↑" : diff < 0 ? "↓" : "—",
        ]);
      }
      if (row.name === "风险等级") {
        const direction = row.direction || "same";
        const color =
          direction === "better"
            ? "#52c41a"
            : direction === "worse"
            ? "#f5222d"
            : "#666";
        const text =
          direction === "better"
            ? "风险降低 ↓"
            : direction === "worse"
            ? "风险升高 ↑"
            : "无变化";
        return h("span", { style: { color, fontWeight: "bold" } }, text);
      }
      return h("span", row.change || "-");
    },
  },
]);

// 维度对比表格列配置
const dimensionColumns = computed<TableColumn[]>(() => [
  {
    label: "维度名称",
    prop: "dimension_name",
    show: true,
  },
  {
    label: "基准扣分",
    prop: "base_deduction",
    align: "right",
    show: true,
    render: (row) => {
      return h("span", (row.base_deduction || 0).toFixed(2));
    },
  },
  {
    label: "对比扣分",
    prop: "compare_deduction",
    align: "right",
    show: true,
    render: (row) => {
      return h("span", (row.compare_deduction || 0).toFixed(2));
    },
  },
  {
    label: "差异",
    prop: "diff",
    align: "right",
    show: true,
    render: (row) => {
      const diff = row.diff || 0;
      const color = diff > 0 ? "#f5222d" : diff < 0 ? "#52c41a" : "#666";
      return h("span", { style: { color, fontWeight: "bold" } }, [
        diff > 0 ? "+" : "",
        diff.toFixed(2),
      ]);
    },
  },
  {
    label: "变化说明",
    prop: "change_description",
    minWidth: 200,
    show: true,
    showOverflowTooltip: true,
  },
  {
    label: "趋势",
    prop: "trend",
    width: 80,
    align: "center",
    show: true,
    render: (row) => {
      const diff = row.diff || 0;
      if (diff > 0) {
        return h(
          "span",
          { style: { color: "#f5222d", fontSize: "20px" } },
          "↑"
        );
      } else if (diff < 0) {
        return h(
          "span",
          { style: { color: "#52c41a", fontSize: "20px" } },
          "↓"
        );
      } else {
        return h("span", { style: { color: "#999" } }, "—");
      }
    },
  },
]);

// 总体对比数据
const overallCompareData = computed(() => {
  if (!compareData.value) return [];

  const { base, compare, differences } = compareData.value;
  return [
    {
      name: "总分",
      baseValue: base?.total_score,
      compareValue: compare?.total_score,
      diff: differences?.total_score_diff || 0,
      change: formatScoreChange(differences?.total_score_diff || 0),
    },
    {
      name: "风险等级",
      baseValue: base?.risk_level,
      compareValue: compare?.risk_level,
      baseDesc: base?.risk_level_desc,
      compareDesc: compare?.risk_level_desc,
      changed: differences?.risk_level_changed || false,
      direction: differences?.risk_level_direction || "same",
      change: formatRiskChange(differences?.risk_level_direction || "same"),
    },
  ];
});

// 维度对比数据
const dimensionCompareData = computed(() => {
  if (!compareData.value || !compareData.value.differences?.dimension_diffs) {
    return [];
  }

  const diffs = compareData.value.differences.dimension_diffs;
  return Object.keys(diffs).map((key) => {
    const dim = diffs[key];
    return {
      dimension_code: key,
      dimension_name: dim.dimension_name || key,
      base_deduction: dim.base_deduction || 0,
      compare_deduction: dim.compare_deduction || 0,
      diff: dim.diff || 0,
      change_description: dim.change_description || "无变化",
    };
  });
});

// 辅助函数 - 格式化分数变化
const formatScoreChange = (diff: number) => {
  if (diff === 0) return "无变化";
  const sign = diff > 0 ? "+" : "";
  return `${sign}${diff.toFixed(1)} 分`;
};

// 辅助函数 - 格式化风险变化
const formatRiskChange = (direction: string) => {
  const map: Record<string, string> = {
    better: "风险降低 ↓",
    worse: "风险升高 ↑",
    same: "无变化",
  };
  return map[direction] || direction;
};

// 辅助函数 - 风险等级样式和文本
const getRiskClass = (level: string) => {
  const classMap: Record<string, string> = {
    low: "bg-success",
    medium: "bg-warning",
    high: "bg-orange-500",
    critical: "bg-danger",
    safe: "bg-info",
  };
  return classMap[level] || "bg-gray-400";
};

const getRiskText = (level: string) => {
  const textMap: Record<string, string> = {
    low: "低风险",
    medium: "中等风险",
    high: "高风险",
    critical: "严重风险",
    safe: "安全",
  };
  return textMap[level] || level;
};

// 辅助函数 - 分数样式
const getScoreClass = (score: number) => {
  if (!score) return "";
  if (score >= 80) return "text-success font-medium";
  if (score >= 60) return "text-warning font-medium";
  return "text-danger font-medium";
};

// 事件处理 - 关闭对话框
const handleClose = () => {
  emit("update:modelValue", false);
  emit("close");
};

// 事件处理 - 导出对比报告
const handleExportReport = () => {
  ElMessage.info("正在导出对比报告...");
  // 导出报告的逻辑
};
</script>

<style scoped lang="scss">
.compare-content {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.compare-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.time-selectors {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 10px 0;
}

.time-select-item {
  display: flex;
  align-items: center;
}

.time-label {
  width: 60px;
  font-weight: 500;
}

.risk-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 4px;
}
</style>
